package patrol.mobile.com.mobilepatrol.activity.road_survey;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import patrol.mobile.com.mobilepatrol.AppConfig;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.FragmentTabAdapter;
import patrol.mobile.com.mobilepatrol.bean.RouteSurveyTaskStructBO;
import patrol.mobile.com.mobilepatrol.bean.TrafficInvestBaseInfo;
import patrol.mobile.com.mobilepatrol.fragment.BaseRoadFragment;
import patrol.mobile.com.mobilepatrol.fragment.InvestBlockTopFragment2;
import patrol.mobile.com.mobilepatrol.fragment.InvestQiaoSuiFragment2;
import patrol.mobile.com.mobilepatrol.fragment.InvestRoadAlongFragment2;
import patrol.mobile.com.mobilepatrol.fragment.InvestRoadBedFragment2;
import patrol.mobile.com.mobilepatrol.fragment.InvestRoadPavementFragment2;
import patrol.mobile.com.mobilepatrol.fragment.InvestRoadSandFragment2;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.UIHelper;


/**
 * Created by 健 on 2014/8/30.
 */
public class TrafficInvestDetailActivity2 extends BaseActivity {
    private TabLayout tabLayout;
    private ViewPager mViewPager;
    private FragmentPagerAdapter fAdapter;

    private List<Fragment> list_fragment;
    private List<String> list_title;

    private BaseRoadFragment f1;
    private BaseRoadFragment f2;
    private BaseRoadFragment f3;
    private BaseRoadFragment f4;
    private BaseRoadFragment f5;
    private BaseRoadFragment f6;
    private TrafficInvestBaseInfo investBaseInfo;
    private String roadType;
    private RouteSurveyTaskStructBO taskStruct;
    private int pos;
    private EditText startPot;
//    private EditText endPot;
    private EditText roadLength;
    private EditText roadWidth;
    private Spinner roadWidthSpi;
    private int tabID = 0;

    @BindView(R.id.tv_tip)
    TextView lastUpdatePageTip;
    @Override
    public void initView() {
        super.initView();

        startPot = (EditText) findViewById(R.id.fragment_invest_startPot);
//        endPot = (EditText) findViewById(R.id.fragment_invest_endPot);
        roadLength = (EditText) findViewById(R.id.fragment_invest_roadLength);
        roadWidth = (EditText) findViewById(R.id.fragment_invest_roadWidth);
        roadWidthSpi = (Spinner) findViewById(R.id.fragment_invest_roadWidth_Spi);

        taskStruct= (RouteSurveyTaskStructBO) getIntent().getSerializableExtra(UIHelper.TASK_STRUCT_INFO);
        //路段
        pos=  getIntent().getIntExtra("pos",-1);

        investBaseInfo= (TrafficInvestBaseInfo) getIntent().getSerializableExtra(UIHelper.INVEST_INFO);
        //路面类型，沥青路面，水泥路面，砂石路面
        roadType=investBaseInfo.getRoudBedType();


        tabLayout = (TabLayout)findViewById(R.id.tab_title);
        mViewPager = (ViewPager)findViewById(R.id.vp_pager);

        //初始化各fragment
//        water = new WaterOrderListFragment();
//        elec = new ElecOrderListFragment();






        //将fragment装进列表中
        list_fragment = new ArrayList<>();

        //将名称加载tab名字列表，正常情况下，我们应该在values/arrays.xml中进行定义然后调用
        list_title = new ArrayList<>();
        if (investBaseInfo.getLumian()==1){
            switch (roadType){
                case "沥青路面":
                    list_title.add("沥青路面调查");
                    f1 = new InvestBlockTopFragment2(pos,taskStruct,investBaseInfo,"沥青路面");
                    list_fragment.add(f1);
                    break;
                case "水泥路面":
                    list_title.add("水泥路面调查");
                    f5 = new InvestRoadPavementFragment2(pos,taskStruct,investBaseInfo,"水泥路面");
                    list_fragment.add(f5);
                    break;
                case "砂石路面":
                    list_title.add("砂石路面调查");
                    f6 = new InvestRoadSandFragment2(pos,taskStruct,investBaseInfo,"砂石路面");
                    list_fragment.add(f6);
                    break;
            }
        }
        if(investBaseInfo.getLuji()==1){
            list_title.add("路基调查");
            f4 = new InvestRoadBedFragment2(pos,taskStruct,investBaseInfo,"路基损坏");
            list_fragment.add(f4);
        }
        if(investBaseInfo.getYanxian()==1){
            list_title.add("沿线设施调查");
            f3 = new InvestRoadAlongFragment2(pos,taskStruct,investBaseInfo,"沿线设施");
            list_fragment.add(f3);
        }
        if(investBaseInfo.getQiaosui()==1){
            list_title.add("桥隧涵调查");
            f2 = new InvestQiaoSuiFragment2(pos,taskStruct,investBaseInfo,"桥隧构造物");
            list_fragment.add(f2);
        }

        //设置TabLayout的模式
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        //为TabLayout添加tab名称
        for (int i=0;i<list_title.size();i++){
            tabLayout.addTab(tabLayout.newTab().setText(list_title.get(i)));
        }

        fAdapter = new FragmentTabAdapter(getSupportFragmentManager(),list_fragment,list_title);

        mViewPager.setAdapter(fAdapter);
        tabLayout.setupWithViewPager(mViewPager,false);
        updateLastUpdatePageTip();
    }
    @Override
    public void initTitle() {
        super.initTitle();

        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.hiddenKeyBoard(TrafficInvestDetailActivity2.this);
                CommonUtil.exitActivityAndBackAnim(TrafficInvestDetailActivity2.this,true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("记录");
        tv_right_title.setVisibility(View.VISIBLE);
        tv_right_title.setText("保存");
        tv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //tab
                String title = list_title.get(tabID);
                switch (title){
                    case "沥青路面调查":
                        Log.d("shj--",tabID+"沥青路面调查"+" 路段"+pos);
                        f1.saveData();
                        break;
                    case "水泥路面调查":
                        f5.saveData();

                    break;
                    case "砂石路面调查":
                        f6.saveData();
                    break;
                    case "路基调查":
                       f4.saveData();
                    break;
                    case "沿线设施调查":
                        f3.saveData();
                    break;
                    case "桥隧涵调查":
                        f2.saveData();
                    break;
                }
                updateLastUpdatePageTip();
                //page
//                showToast(tabID+"");
            }
        });

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.traffic_invest_detail_view2;
    }

    @Override
    public void setListener() {
        roadWidthSpi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv = (TextView) view;
                if(tv==null)
                    return;
                tv.setTextAppearance(TrafficInvestDetailActivity2.this, R.style.singleline_text);

                String str = roadWidthSpi.getAdapter().getItem(i).toString();
                if (str.equals("---手动输入---")) {
                    roadWidth.setVisibility(View.VISIBLE);
                    roadWidth.requestFocus();
                } else {
                    roadWidth.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabID = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        roadWidthSpi.setAdapter(getArrayAdapter(getResources().getStringArray(R.array.invest_road_width)));
        startPot.setText(taskStruct.getStartPotName()+"-"+taskStruct.getEndPotName());
//        endPot.setText(taskStruct.getEndPotName());
        roadLength.setText(taskStruct.getRoadLength()+"");
        roadWidth.setText(taskStruct.getRoadWidth()+"");
        String rWidth=StringUtils.formatInvestNum(taskStruct.getRoadWidth());
        int index=-1;
        for(int i=0;i<roadWidthSpi.getAdapter().getCount();i++){
            if(roadWidthSpi.getAdapter().getItem(i).equals(rWidth)){
                index=i;
                break;
            }
        }
        if(index!=-1){
            roadWidthSpi.setSelection(index);
        }else if(!StringUtils.isEmpty(rWidth)){
            roadWidthSpi.setSelection(roadWidthSpi.getAdapter().getCount()-1);
            roadWidth.setText(rWidth);
        }else{
            roadWidthSpi.setSelection(0);
        }

    }
    public double getCurrentRoadWidth(){
        if(roadWidth.getVisibility()==View.VISIBLE)
            return getDoubleValue(roadWidth);
        else
            return Double.valueOf(roadWidthSpi.getSelectedItem().toString());
    }
    public double getDoubleValue(EditText editText){
        return getDoubleValue(editText.getText().toString());
    }
    private double getDoubleValue(String str){
        double result=0;
        if(!StringUtils.isEmpty(str)){
            if(str.contains("+")){
                String[] strings=str.split("\\+");
                if(strings.length==2)
                    result=getDoubleValue(strings[0])+getDoubleValue(strings[1]);
                else if(strings.length==1)
                    result=getDoubleValue(strings[0]);
            }else if(!str.equals("."))
                result=Double.valueOf(str);
        }

        return result;
    }
    private void updateLastUpdatePageTip(){
                String lastUpdatePage= AppConfig.getAppConfig(getApplicationContext()).get(AppConfig.CONF_INVEST_LAST_PAGE);
                if(!StringUtils.isEmpty(lastUpdatePage)&&lastUpdatePage.startsWith(taskStruct.getiD())){
                    String[] data= lastUpdatePage.substring(taskStruct.getiD().length()).split("-");
                    lastUpdatePageTip.setText(Html.fromHtml(getString(R.string.invest_last_update_page_tip,data[1],data[2])));
                }else{
                    lastUpdatePageTip.setText("");
                }
    }
}
